package cn.xxluckey.core;

import java.util.concurrent.ConcurrentHashMap;

public class SessionManager {

    private static class Session {
        private boolean loggedIn; // 登录状态
        private int sequenceNumber; // 当前序列号

        public Session() {
            this.loggedIn = false;
            this.sequenceNumber = 0;
        }

        public boolean isLoggedIn() {
            return loggedIn;
        }

        public void setLoggedIn(boolean loggedIn) {
            this.loggedIn = loggedIn;
        }

        public int getSequenceNumber() {
            return sequenceNumber;
        }

        public void incrementSequenceNumber() {
            this.sequenceNumber++;
        }

        public void resetSequenceNumber() {
            this.sequenceNumber = 0;
        }
    }

    private final ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * 获取充电桩的会话状态
     * @param chargerId 充电桩唯一标识
     * @return 会话状态
     */
    public Session getSession(String chargerId) {
        return sessionMap.computeIfAbsent(chargerId, id -> new Session());
    }

    /**
     * 登录充电桩
     * @param chargerId 充电桩唯一标识
     */
    public void login(String chargerId) {
        Session session = getSession(chargerId);
        session.setLoggedIn(true);
        session.resetSequenceNumber(); // 登录时序列号归 0
    }

    /**
     * 注销充电桩
     * @param chargerId 充电桩唯一标识
     */
    public void logout(String chargerId) {
        Session session = getSession(chargerId);
        session.setLoggedIn(false);
        session.resetSequenceNumber(); // 断开连接时序列号归 0
    }

    /**
     * 获取当前序列号并递增
     * @param chargerId 充电桩唯一标识
     * @return 当前序列号
     */
    public int getAndIncrementSequenceNumber(String chargerId) {
        Session session = getSession(chargerId);
        int current = session.getSequenceNumber();
        session.incrementSequenceNumber();
        return current;
    }
}

